TOOL.Category = "Weapons"
TOOL.Name = "#Dakara Superweapon"
TOOL.Command = nil
TOOL.ConfigName = ""
TOOL.Tab = "Stargate"
TOOL.AddToMenu = false -- Tell GMod not to add this STool. aVoN's code will do it later.

local entityName = "dakara"

local models = 
{
   "models/Dakara_Weapon/dakara_weapon.mdl",
   "models/props_combine/breenglobe.mdl"
}

TOOL.ClientConVar['target_players'] = "0"
TOOL.ClientConVar['safe_zone_radius'] = "0"
TOOL.ClientConVar['target_npcs'] = "0"
TOOL.ClientConVar['target_props'] = "0"
TOOL.ClientConVar['target_custom'] = ""
TOOL.ClientConVar['model'] = models[1]

cleanup.Register(entityName)

if(CLIENT) then
	language.Add("Tool_"..entityName.."_name", 'Dakara Superweapon')
	language.Add("Tool_"..entityName.."_desc", 'Creates the Dakara superweapon.')
	language.Add("Tool_"..entityName.."_0", 'Left click to create the Dakara superweapon.   Right click on something to make that type of object a target.')
	language.Add("Undone_"..entityName, 'Dakara Superweapon Undone')
	language.Add("Cleanup_"..entityName, 'Dakara Superweapons')
	language.Add("Cleaned_"..entityName, 'Removed all Dakara superweapons')
	language.Add("SBoxLimit_"..entityName, 'Maximum number of Daraka superweapons created')
end

if(SERVER) then 
    CreateConVar("sbox_max"..entityName, 2)
    
	function TOOL:MakeEntity(player, position, upVector, angle)
		if(!player:CheckLimit(entityName)) then 
         return nil 
      end
        
		local entity = ents.Create(entityName)
      
      if(entity == nil || entity:IsValid() == false) then
         error("Could not spawn "..entityName..".\n")
      end
      
      entity:SetModel(self:GetClientInfo("model"))
      entity:SetAngles(angle)
      entity:SetPos(position + upVector * entity:BoundingRadius())
      entity:SetVar("Owner", player)
      entity:Setup(self:GetTargets(), self:GetClientNumber("safeZoneRadius"))
		entity:Spawn()
        
		player:AddCount(entityName, entity)
		return entity
	end
end

function TOOL:LeftClick(trace)
	if(trace.Entity && trace.Entity:IsPlayer()) then 
      return false 
   elseif(CLIENT) then 
      return true 
   elseif(!self:GetSWEP():CheckLimit(entityName)) then 
      return false 
   end
   
   local player = self:GetOwner()
   
	local angle = trace.HitNormal:Angle()
   angle.pitch = angle.pitch + 90
   angle.yaw = trace.Normal:Angle().yaw
   
   entity = self:MakeEntity(player, 
                            trace.HitPos, 
                            trace.HitNormal, 
                            angle)
    
	if(trace.HitNonWorld) then
		weld = constraint.Weld(entity, trace.Entity, 0, trace.PhysicsBone, 0, true)
		noCollide = constraint.NoCollide(entity, trace.Entity, 0, trace.PhysicsBone)
		trace.Entity:DeleteOnRemove(entity)
	else
		local physics = entity:GetPhysicsObject()
		
      if(physics:IsValid()) then
			physics:Wake()
			physics:EnableMotion(true)
		end
	end
    
	undo.Create(entityName)
	undo.AddEntity(entity)
    
	if(trace.Entity:IsValid()) then
		undo.AddEntity(weld)
		undo.AddEntity(noCollide)
	end
    
	undo.SetPlayer(player)
	undo.Finish()
	player:AddCleanup(entityName, entity)
    
	return true
end

function TOOL:RightClick(trace)
   if(trace.Entity == nil) then
      return false
   elseif(CLIENT) then
      return true
   end
   
   local entity = trace.Entity
   
   if(trace.Entity:GetClass() == entityName) then
      return entity:Setup(self:GetTargets(), self:GetClientNumber("safeZoneRadius"))
   else
      local targetName = entity:GetClass()
      
      self:SetClientInfo("target_custom", targetName)
      --self:GetOwner():ConCommand("target_custom "..targetName);
   end
   
   return true
end

function TOOL:GetTargets()
   local targets = {}
   
   if(self:GetClientNumber("target_players") ~= 0) then
      table.insert(targets, "player")
   end
   
   if(self:GetClientNumber("target_npcs") ~= 0) then
      table.insert(targets, "npc")
   end
   
   if(self:GetClientNumber("target_props") ~= 0) then
      table.insert(targets, "prop")
   end
   
   local customTarget = self:GetClientInfo("target_custom")
   
   if(customTarget ~= "") then
      table.insert(targets, customTarget)
   end
   
   return targets
end

function TOOL.BuildCPanel(panel)
	panel:AddControl('Header', 
   {
      Text = "#Tool_"..entityName.."_name", 
      Description = "#"..entityName
   })
   
   panel:AddControl("CheckBox", 
   {
		Label = "Disintegrate Players?",
		Description = "Should all players caught in the energy wave be disintegrated?",
		Command = entityName.."_target_players"
	})
   
   panel:AddControl("CheckBox", 
   {
		Label = "Disintegrate NPCs?",
		Description = "Should all NPCs caught in the energy wave be disintegrated?",
		Command = entityName.."_target_npcs"
	})
   
   panel:AddControl("CheckBox", 
   {
		Label = "Disintegrate Props?",
		Description = "Should all props caught in the energy wave be disintegrated?",
		Command = entityName.."_target_props"
	})
   
   panel:AddControl("TextBox", 
   {
		Label = "Custom Target:",
		Description = "Enter the class name of the type of object you want to disintegrate.",
		Command = entityName.."_target_custom"
	})
   
   for _, model in pairs(models) do
      if(file.Exists("../"..model)) then
         list.Set(entityName.."Models", model, {})
      end
   end
   
   panel:AddControl("PropSelect", 
   {
		Label = "Model:",
		ConVar = entityName.."_model",
		Category = "Stargate",
		Models = list.Get(entityName.."Models")
   })
   
   panel:AddControl("Slider", 
   {
      Label = "Safe Zone Radius:", 
      Type = "Integer", 
      Min = 0, Max = 500, 
      Command = entityName.."_safe_zone_radius"
   })
end
